<?php
class Banners extends CActiveRecord {
    
    public $bannerId;
    public $code;
    public $type;
    
    public $cats;
    
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }
    
    public function beforeValidate() {
        if(!parent::beforeValidate()) return false;
        $this->attributes = !empty($_POST[get_class($this)]) ? $_POST[get_class($this)] : array();
        return true;
    }
    
    public function rules() {
        return array(
            array('type, cats', 'safe'),
            array('code', 'required')
        );
    }

    public function tableName() {
        return 'banners';
    }
    
    public function beforeSave() {
        if(!parent::beforeSave()) return false;
        if(empty($this->cats)) {
            $this->addError('','Выберите категорию');
            return false;
        }
        return true;
    }        
    
    public function afterSave() {
        Yii::app()->db->createCommand()->delete('banners_relations', 'bannerId='.$this->bannerId);
        if(!empty($this->cats)) {
            foreach ($this->cats as $c)
                Yii::app()->db->createCommand()->insert('banners_relations', array('catId'=>$c, 'bannerId'=>$this->bannerId));
        }
    }
    
    public function afterDelete() {
        Yii::app()->db->createCommand()->delete('banners_relations', 'bannerId='.$this->bannerId);
    }
    
    public function attributeLabels() {
        return array(
            'type'=>'Тип',
            'code'=>'Код'
        );
    }
}
